import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { FiBarChart, FiTarget, FiTrendingUp, FiClock, FiBook, FiAward, FiCalendar, FiTrash2 } from 'react-icons/fi';

interface LearningSession {
  id: string;
  date: string;
  wordsCount: number;
  scenesGenerated: number;
  timeSpent: number;
  words: string[];
}

const ProgressTracker: React.FC = () => {
  const [sessions, setSessions] = useState<LearningSession[]>(() => {
    const saved = localStorage.getItem('learningSessions');
    return saved ? JSON.parse(saved) : [];
  });

  const [showConfirmDelete, setShowConfirmDelete] = useState<string | null>(null);

  // 计算统计数据
  const totalWords = sessions.reduce((sum, session) => sum + session.wordsCount, 0);
  const totalScenes = sessions.reduce((sum, session) => sum + session.scenesGenerated, 0);
  const totalTime = sessions.reduce((sum, session) => sum + session.timeSpent, 0);
  const uniqueWords = [...new Set(sessions.flatMap(session => session.words))].length;

  // 删除学习记录
  const deleteSession = (sessionId: string) => {
    const updatedSessions = sessions.filter(session => session.id !== sessionId);
    setSessions(updatedSessions);
    localStorage.setItem('learningSessions', JSON.stringify(updatedSessions));
    setShowConfirmDelete(null);
  };

  // 格式化时间
  const formatTime = (minutes: number) => {
    if (minutes < 60) return `${minutes}分钟`;
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${hours}小时${mins > 0 ? `${mins}分钟` : ''}`;
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="max-w-4xl mx-auto p-4 sm:p-6 space-y-4 sm:space-y-6">
      {/* 页面标题 */}
      <motion.div 
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center space-y-2"
      >
        <h1 className="text-2xl sm:text-3xl font-bold bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent">
          学习进度追踪
        </h1>
        <p className="text-gray-600 text-sm sm:text-base">记录您的学习足迹，见证成长历程</p>
      </motion.div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="bg-gradient-to-br from-blue-50 to-indigo-100 rounded-xl p-4 sm:p-6 border border-blue-200"
        >
          <div className="flex items-center justify-between mb-2">
            <FiBook className="text-blue-600 w-5 h-5 sm:w-6 sm:h-6" />
            <span className="text-xs sm:text-sm text-blue-600 font-medium">总词汇</span>
          </div>
          <div className="text-xl sm:text-2xl font-bold text-blue-700">{totalWords}</div>
          <div className="text-xs sm:text-sm text-blue-600 mt-1">学习单词数</div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 sm:p-6 border border-purple-200"
        >
          <div className="flex items-center justify-between mb-2">
            <FiTarget className="text-purple-600 w-5 h-5 sm:w-6 sm:h-6" />
            <span className="text-xs sm:text-sm text-purple-600 font-medium">独特词汇</span>
          </div>
          <div className="text-xl sm:text-2xl font-bold text-purple-700">{uniqueWords}</div>
          <div className="text-xs sm:text-sm text-purple-600 mt-1">不重复单词</div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="bg-gradient-to-br from-green-50 to-emerald-100 rounded-xl p-4 sm:p-6 border border-green-200"
        >
          <div className="flex items-center justify-between mb-2">
            <FiBarChart className="text-green-600 w-5 h-5 sm:w-6 sm:h-6" />
            <span className="text-xs sm:text-sm text-green-600 font-medium">生成场景</span>
          </div>
          <div className="text-xl sm:text-2xl font-bold text-green-700">{totalScenes}</div>
          <div className="text-xs sm:text-sm text-green-600 mt-1">学习场景数</div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl p-4 sm:p-6 border border-orange-200"
        >
          <div className="flex items-center justify-between mb-2">
            <FiClock className="text-orange-600 w-5 h-5 sm:w-6 sm:h-6" />
            <span className="text-xs sm:text-sm text-orange-600 font-medium">学习时长</span>
          </div>
          <div className="text-xl sm:text-2xl font-bold text-orange-700">{formatTime(totalTime)}</div>
          <div className="text-xs sm:text-sm text-orange-600 mt-1">累计时间</div>
        </motion.div>
      </div>

      {/* 学习历史 */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.5 }}
        className="bg-white rounded-xl shadow-lg border border-gray-200"
      >
        <div className="p-4 sm:p-6 border-b border-gray-200">
          <div className="flex items-center gap-2 sm:gap-3">
            <FiCalendar className="text-gray-600 w-5 h-5 sm:w-6 sm:h-6" />
            <h2 className="text-lg sm:text-xl font-semibold text-gray-800">学习历史</h2>
            <span className="text-xs sm:text-sm text-gray-500 ml-auto">{sessions.length} 次学习</span>
          </div>
        </div>

        <div className="max-h-96 overflow-y-auto">
          {sessions.length === 0 ? (
            <div className="p-8 sm:p-12 text-center">
              <div className="w-16 h-16 sm:w-20 sm:h-20 mx-auto mb-4 bg-gradient-to-br from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
                <FiBook className="text-gray-400 w-8 h-8 sm:w-10 sm:h-10" />
              </div>
              <h3 className="text-lg sm:text-xl font-semibold text-gray-700 mb-2">还没有学习记录</h3>
              <p className="text-gray-500 text-sm sm:text-base">开始您的英语学习之旅，创建第一个场景吧！</p>
              <motion.div
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.3, type: "spring", bounce: 0.4 }}
                className="mt-4 text-2xl sm:text-3xl"
              >
                🚀
              </motion.div>
            </div>
          ) : (
            <div className="space-y-0">
              {sessions.map((session, index) => (
                <motion.div
                  key={session.id}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: index * 0.1 }}
                  className="p-4 sm:p-6 border-b border-gray-100 last:border-b-0 hover:bg-gray-50 transition-colors group"
                >
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4">
                    <div className="flex-1">
                      <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4 mb-2">
                        <div className="flex items-center gap-2">
                          <FiAward className="text-indigo-600 w-4 h-4 sm:w-5 sm:h-5" />
                          <span className="font-medium text-gray-800 text-sm sm:text-base">
                            学习会话 #{sessions.length - index}
                          </span>
                        </div>
                        <span className="text-xs sm:text-sm text-gray-500">
                          {formatDate(session.date)}
                        </span>
                      </div>
                      
                      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 sm:gap-4 text-xs sm:text-sm">
                        <div className="flex items-center gap-1.5">
                          <FiBook className="text-blue-600 w-3 h-3 sm:w-4 sm:h-4" />
                          <span className="text-gray-600">{session.wordsCount} 个单词</span>
                        </div>
                        <div className="flex items-center gap-1.5">
                          <FiBarChart className="text-green-600 w-3 h-3 sm:w-4 sm:h-4" />
                          <span className="text-gray-600">{session.scenesGenerated} 个场景</span>
                        </div>
                        <div className="flex items-center gap-1.5 col-span-2 sm:col-span-1">
                          <FiClock className="text-orange-600 w-3 h-3 sm:w-4 sm:h-4" />
                          <span className="text-gray-600">{formatTime(session.timeSpent)}</span>
                        </div>
                      </div>

                      {session.words.length > 0 && (
                        <div className="mt-3 flex flex-wrap gap-1.5 sm:gap-2">
                          {session.words.slice(0, 6).map((word, wordIndex) => (
                            <span
                              key={wordIndex}
                              className="px-2 py-1 bg-gradient-to-r from-indigo-100 to-purple-100 text-indigo-700 rounded-full text-xs font-medium"
                            >
                              {word}
                            </span>
                          ))}
                          {session.words.length > 6 && (
                            <span className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs">
                              +{session.words.length - 6}
                            </span>
                          )}
                        </div>
                      )}
                    </div>

                    <div className="flex items-center gap-2">
                      <motion.button
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                        onClick={() => setShowConfirmDelete(session.id)}
                        className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all opacity-0 group-hover:opacity-100"
                      >
                        <FiTrash2 size={16} />
                      </motion.button>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </div>
      </motion.div>

      {/* 删除确认对话框 */}
      <AnimatePresence>
        {showConfirmDelete && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
            onClick={() => setShowConfirmDelete(null)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="bg-white rounded-xl shadow-xl p-6 max-w-sm w-full mx-4"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="text-center">
                <div className="w-12 h-12 mx-auto mb-4 bg-red-100 rounded-full flex items-center justify-center">
                  <FiTrash2 className="text-red-600 w-6 h-6" />
                </div>
                <h3 className="text-lg font-semibold text-gray-800 mb-2">确认删除</h3>
                <p className="text-gray-600 mb-6 text-sm">
                  确定要删除这条学习记录吗？此操作无法撤销。
                </p>
                <div className="flex gap-3">
                  <button
                    onClick={() => setShowConfirmDelete(null)}
                    className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm font-medium"
                  >
                    取消
                  </button>
                  <button
                    onClick={() => deleteSession(showConfirmDelete)}
                    className="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm font-medium"
                  >
                    删除
                  </button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default ProgressTracker;